<template>
  <div class="my_page">
    <el-card class="box-card">
      <div class="padding_15">
        <new-steps :stepList="stepList" :stepActive="stepActive" @change="changeStepActive" :disabled="!isEditorMode"></new-steps>
      </div>
    </el-card>
    <!-- 失活的组件将会被缓存！-->
    <el-card class="page-body">
      <keep-alive>
        <component :store-id.sync="storeId" :store-no.sync="storeSPUNo" :class-id="storeClassId" :supply-id="supplyId" :new-attr.sync="newAttrList" :storeAttrListAll="allAttrList" :detail="storeDetail" :price-list="priceTypeList" :size-list="sizeTypeList" ref="FormComponentRef" v-bind:is="currentFormComponent"></component>
      </keep-alive>
      <div>
        <br>
        <el-button @click="goBack">取消</el-button>

        <el-button type="primary" @click="backOption" v-if="stepActive != 1">上一步</el-button>
        <el-button type="primary" @click="nextOption" v-if="stepActive != stepList.length">下一步</el-button>
        <el-button type="primary" @click="comfirmOption" v-if="stepActive == 1">保存</el-button>
        <el-button type="primary" @click="comfirmOption" v-if="stepActive == 3">保存（提交审核）</el-button>
        <!-- <el-button type="primary" @click="comfirmOption" v-if="isEditorMode == true && stepActive == 3">保存</el-button> -->
        
        <!-- || stepActive == 3 -->
      </div>
    </el-card>
  </div>
</template>

<script>
import Setting from '@/settings';
import NewSteps from '@/components/NewSteps/index';
import NewBaseForm from '@/views/store-management/components/newBaseForm';
import NewSkuForm from '@/views/store-management/components/newSkuForm';
import NewChannelForm from '@/views/store-management/components/newChannelForm';

import { GetStoreItemDetailNewCopy, GetAllStorePriceModel, GetStoreAttrListAllByParams,
 InsertStoreItem, UpdateStoreItem, UpdateGoodsMarketing, GetSizeListCopy } from '@/views/store-management/services/index';

export default {
  components: {
    NewSteps,
    NewBaseForm,
    NewSkuForm,
    NewChannelForm
  },
  data() {
    return {
      stepList: [
        '基础设置',
        'SKU信息',
        '营销设置'
      ],
      stepActive: 1,

      // 组件切换控制
      formComponentList: [NewBaseForm, NewSkuForm, NewChannelForm],

      storeId: '',
      storeSPUNo: '',
      storeClassId: '',
      storeDetail: null,
      allAttrList: [],
      newAttrList: [],
      isEditorMode: false, // 编辑模式
      justGenerateId: false,
      priceTypeList: [],
      sizeTypeList: [],
      supplyId: ''
    }
  },
  computed: {
    currentFormComponent() {
      return this.formComponentList[this.stepActive - 1];
    }
  },
  created() {
    this.getPriceModelList();
    this.getSizeModelList();
    this.getStoreAttrList();
    if (this.$route.params.id) {
      this.isEditorMode = true;
      this.storeId = this.$route.params.id;

      this.getStoreDetail();
    }
  },
  methods: {
    // 上一步点击事件
    backOption() {
      this.isStoreAttrChange = false;
      this.stepActive -= 1;
    },
    changeStepActive(data) {
      this.stepActive = data
    },
    // 完成点击按钮
    comfirmOption() {
      switch (this.stepActive.toString()) {
        case '1':
          if (!this.validForm()) return;
          if (!this.isEditorMode) {
            this.addStoreApi();
          } else {
            this.updateStoreApi();
          }
          break;
        case '2':
          this.stepActive += 1;
          break;
        default:
          break;
        case '3':
          // this.stepActive += 1;
          this.lastStep()
        break;
      }
    },
    // 点击取消返回首页
    goBack() {
      this.$router.go(-1);
    },

    // 下一步事件
    nextOption() {
      console.log(this.stepActive.toString())
      switch (this.stepActive.toString()) {
        case '1':
          if (!this.validForm()) return;
          if (!this.isEditorMode) {
            this.addStoreApi();
          } else {
            this.updateStoreApi();
          }
          break;
        case '2':
          this.stepActive += 1;
          break;
        default:
          break;  
      }
    },

    // 验证表单
    validForm() {
      const baseFormData = this.$refs.FormComponentRef;
      if (!baseFormData.baseInfoForm.storeTitle) {
        this.$message.warning('请输入商品名称!');
        return false;
      }
      if (!baseFormData.baseInfoForm.storeClass.length) {
        this.$message.warning('请选择商品分类!');
        return false;
      }
      if (baseFormData.baseInfoForm.storeClass.length < 3) {
        this.$message.warning('商品分类不完整，请选择到第三级商品分类!');
        return false;
      }
      if (!baseFormData.baseInfoForm.storeBrand || !baseFormData.baseInfoForm.storeBrand.value) {
        this.$message.warning('请选择商品品牌!');
        return false;
      }
      if (!baseFormData.baseInfoForm.storeSupply || !baseFormData.baseInfoForm.storeSupply.value) {
        this.$message.warning('请选择商品供应商!');
        return false;
      }
      // if (!baseFormData.baseInfoForm.storeTaxNo) {
      //   this.$message.warning('请输入商品税码!');
      //   return false;
      // }
      // if (!Setting.expression[0].value.test(baseFormData.baseInfoForm.storeTaxNo)) {
      //   this.$message.warning('商品税码格式错误!');
      //   return false;
      // }
      // if (baseFormData.baseInfoForm.storeSupplyNo && !Setting.expression[0].value.test(baseFormData.baseInfoForm.storeSupplyNo)) {
      //   this.$message.warning('供应商货号格式错误!');
      //   return false;
      // }
      if (!baseFormData.storeImageList.length) {
        this.$message.warning('请上传商品图片!');
        return false;
      }
      if (baseFormData.storeImageList.length < 2) {
        this.$message.warning('请至少上传两张商品图片!');
        return false;
      }
      return true;
    },

    // 新建数据
    addStoreApi() {
      const loader = this.$loading({
        lock: true,
        fullscreen: true
      });
      InsertStoreItem(this.formatFormData())
      .finally(() => loader.close())
      .then(data => {
        if (data.code == 200) {
          // 上传完信息之后暂存商品id
          this.storeId = data.data.id;
          this.stepActive = 2;
          this.isEditorMode = true; // 进入编辑模式
          this.justGenerateId = true;
        } else {
          this.$message.error('商品新建失败!');
        }
      })
    },

    // 更新数据
    updateStoreApi() {
      const loader = this.$loading({
        lock: true,
        fullscreen: true
      });
      UpdateStoreItem({
        id: this.storeId,
        ...this.formatFormData()
      })
      .finally(() => loader.close())
      .then(data => {
        if (data.code == 200) {
          this.stepActive = 2;
          this.justGenerateId = false;
        } else {
          this.$message.error('商品信息修改失败!');
        }
      })
      .catch(error => {
        this.$message.error('商品信息修改失败!');
      })
    },
    lastStep() {
     const formComponent = this.$refs.FormComponentRef;
      console.log(formComponent)
      if (!formComponent.storeChannel || !formComponent.storeChannel.length) {
        this.$message.warning('请至少选择一种渠道!');
        return;
      }
      const loader = this.$loading({
        lock: true,
        fullscreen: true
      });
      UpdateGoodsMarketing({
        id: this.storeId, // 商品id	
        initVolume: formComponent.storeInitCount, // 初始销量	
        isShare: formComponent.storeIsShared ? 1 : 0, // 是否分享	
        isDistribution: formComponent.storeIsSaled ? 1 : 0, // 是否分销	
        // autoPublish: formComponent.autoPublish ? 1: 0, //是否上架
        cidList: formComponent.storeChannel, // 渠道id列表	
        tagList: formComponent.storeTags, // 标签id列表
      })
      .finally(() => loader.close())
      .then(data => {
        if (data && data.code == 200) {
          this.$message.success('保存成功');
          this.goBack();
        }
      })
    },
    formatFormData() {
      const baseFormData = this.$refs.FormComponentRef;
      const storeImageList = JSON.parse(JSON.stringify(baseFormData.storeImageList));
      storeImageList.splice(0, 1);
      const storeVideoList = JSON.parse(JSON.stringify(baseFormData.storeVideoList)).filter(item => item);
      // 获取可以选择的属性列表（绑定的class没有属性就会取所有的属性）
      this.newAttrList = JSON.parse(JSON.stringify(baseFormData.propertiesList));
      this.storeSPUNo = baseFormData.baseInfoForm.storeSPUNo;
      this.supplyId = baseFormData.baseInfoForm.storeSupply ? baseFormData.baseInfoForm.storeSupply.value : '';
      return {
        mchId: this.$store.getters.userInfo ? JSON.parse(this.$store.getters.userInfo).mchId : '1',
        creatorId: this.$store.getters.userInfo ? JSON.parse(this.$store.getters.userInfo).id : '1',
        mchType: (this.$store.getters.userInfo && JSON.parse(this.$store.getters.userInfo).userType == 1) ? 1 : 0, // 商户类型 默认 0 平台  1 普通商户
        isEntity: baseFormData.baseInfoForm.storeType, // 是否实物商品 0实物商品 1虚拟商品
        title: baseFormData.baseInfoForm.storeTitle, // 标题
        categoryId: baseFormData.baseInfoForm.storeClass[baseFormData.baseInfoForm.storeClass.length - 1], // 商品类目id
        firstCategoryId: baseFormData.baseInfoForm.storeClass[0] ? baseFormData.baseInfoForm.storeClass[0] : '', // 商品一级类目id	
        secondCategoryId: baseFormData.baseInfoForm.storeClass[1] ? baseFormData.baseInfoForm.storeClass[1] : '', // 商品二级类目id	
        thirdCategoryId: baseFormData.baseInfoForm.storeClass[2] ? baseFormData.baseInfoForm.storeClass[2] : '', // 商品三级类目id
        brandId: baseFormData.baseInfoForm.storeBrand ? baseFormData.baseInfoForm.storeBrand.value : '', // 品牌
        supplierId: baseFormData.baseInfoForm.storeSupply ? baseFormData.baseInfoForm.storeSupply.value : '', // 供应商id
        goodsNo: baseFormData.baseInfoForm.storeSPUNo, // 商品编码
        taxNumber: baseFormData.baseInfoForm.storeTaxNo, // 商品税号
        productionTime: baseFormData.baseInfoForm.storeCreateTime, //生产年份
        articleNumber: baseFormData.baseInfoForm.storeSupplyNo, // 商品供应商货号
        leadTime: baseFormData.isShowCustom ? baseFormData.baseInfoForm.storeStartTime + ',' + baseFormData.baseInfoForm.storeEndTime : '',
        subtitle: baseFormData.baseInfoForm.storeSubtitle, // 商品副标题
        surfaceImg: baseFormData.storeImageList[0], // 封面图
        goodsFileList: storeImageList.map((item, index) => {
          return {
            fileType: 1,
            fileUrl: item,
            sort: index + 1
          }
        }).concat(storeVideoList.map((item, index) => {
          return {
            fileType: 2,
            fileUrl: item,
            sort: storeImageList.length + index + 1
          }
        })),
        introduction: baseFormData.storeDetail // 商品详情
      };
    },
    // 获取尺码模板(不分页)
    getSizeModelList() {
       GetSizeListCopy({
         status: 1,
         search: '',
         sort: true,
        //  sortField: ''
       }).then(res=> {
         console.log(res)
         if(res.code == 200) {
           this.sizeTypeList = res.data
         }
       }).catch(err =>{
         console.log(err)
       })
    },
    
    // 获取全部属性
    getStoreAttrList() {
      const loader = this.$loading({
        lock: true,
        fullscreen: true
      });
      GetStoreAttrListAllByParams()
      .finally(() => loader.close())
      .then(data => {
        this.allAttrList = data.data.map(item => {
          return {
            sort: item.sort,
            status: item.status,
            propertyId: item.id,
            propertyName: item.propertyName,
            propertyCode: item.propertyNo
          };
        });
      })
    },
    // 获取商品详情
    getStoreDetail() {
      const loader = this.$loading({
        lock: true,
        fullscreen: true
      });
      GetStoreItemDetailNewCopy({ id: this.storeId })
      .finally(() => {
        loader.close();
        if(this.$route.query.nextStep) {
          setTimeout(() => {
            this.stepActive = this.$route.query.nextStep;
          }, 300)
        }
      })
      .then(data => {
        if (data.code == 200) {
          this.storeDetail = data.data;
          this.storeSPUNo = data.data.goodsNo;
          this.supplyId = this.storeDetail.supplierId;
        }
      })
    },

    getPriceModelList() {
      GetAllStorePriceModel()
      .then(data => {
        if (data.code == 200) {
          this.priceTypeList = data.data.map(item => {
            return {
              name: item.name,
              value: item.id,
              children: JSON.parse(item.selectionPrice.replace(/'/g,'"')).map(childItem => {
                return {
                  priceName: childItem.priceName,
                  fieldName: childItem.fieldName,
                  remark: childItem.remark,
                  value: 0
                }
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.my_page {
  width: 100%;
  min-width: 1180px;
}
.page-body {
  margin-top: 15px;
  padding: 0 0 0 100px;
  box-shadow: none;
}
.box-card {
  box-shadow: none;
}
</style>
